package com.wt.ocr;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.latin.TextRecognizerOptions;

import java.io.IOException;
import java.io.InputStream;

public class DigitalInkRecognitionActivity extends AppCompatActivity {

    private static final String TAG = "DigitalInkRecognition";
    
    private ImageView ivSelectedImage;
    private TextView tvRecognitionResult;
    private Button btnRecognize;
    private Button btnBack;
    
    private Uri imageUri;
    private Bitmap selectedBitmap;
    private TextRecognizer textRecognizer;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_digital_ink_recognition);
        
        initViews();
        initTextRecognizer();
        loadSelectedImage();
        setupClickListeners();
    }

    private void initViews() {
        ivSelectedImage = findViewById(R.id.iv_selected_image);
        tvRecognitionResult = findViewById(R.id.tv_recognition_result);
        btnRecognize = findViewById(R.id.btn_recognize);
        btnBack = findViewById(R.id.btn_back);
        
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在识别文字...");
        progressDialog.setCancelable(false);
    }

    private void initTextRecognizer() {
        // 使用ML Kit的文字识别功能
        textRecognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
    }

    private void loadSelectedImage() {
        String imageUriString = getIntent().getStringExtra("imageUri");
        if (imageUriString != null) {
            imageUri = Uri.parse(imageUriString);
            try {
                InputStream inputStream = getContentResolver().openInputStream(imageUri);
                selectedBitmap = BitmapFactory.decodeStream(inputStream);
                ivSelectedImage.setImageBitmap(selectedBitmap);
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "Error loading image: " + e.getMessage());
                Toast.makeText(this, "加载图片失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            Toast.makeText(this, "未选择图片", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void setupClickListeners() {
        btnRecognize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recognizeText();
            }
        });

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void recognizeText() {
        if (selectedBitmap == null) {
            Toast.makeText(this, "请先选择图片", Toast.LENGTH_SHORT).show();
            return;
        }

        progressDialog.show();
        
        // 创建InputImage对象
        InputImage image = InputImage.fromBitmap(selectedBitmap, 0);
        
        // 开始文字识别
        textRecognizer.process(image)
                .addOnSuccessListener(new OnSuccessListener<Text>() {
                    @Override
                    public void onSuccess(Text visionText) {
                        progressDialog.dismiss();
                        displayRecognitionResult(visionText);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Log.e(TAG, "Text recognition failed: " + e.getMessage());
                        Toast.makeText(DigitalInkRecognitionActivity.this, 
                                "文字识别失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        tvRecognitionResult.setText("识别失败，请重试");
                    }
                });
    }

    private void displayRecognitionResult(Text visionText) {
        String resultText = visionText.getText();
        
        if (resultText.isEmpty()) {
            tvRecognitionResult.setText("未识别到文字内容");
        } else {
            StringBuilder formattedResult = new StringBuilder();
            formattedResult.append("识别结果:\n\n");
            formattedResult.append(resultText);
            
            // 添加详细信息
            formattedResult.append("\n\n--- 详细信息 ---\n");
            for (Text.TextBlock block : visionText.getTextBlocks()) {
                formattedResult.append("文本块: ").append(block.getText()).append("\n");
            }
            
            tvRecognitionResult.setText(formattedResult.toString());
        }
        
        Log.d(TAG, "Recognition result: " + resultText);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (textRecognizer != null) {
            textRecognizer.close();
        }
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}